//
//  ALAssetsGroupEnumerator.m
//  OntheRoadV4
//
//  Created by ZhangYanhua on 15/1/6.
//  Copyright (c) 2015年 EricHuang. All rights reserved.
//

#import "ALAssetsGroupEnumerator.h"
#import "PHAsset+Downscaling.h"
#import "NSDate-Utilities.h"
#import "QWImageMangerConfig.h"
@implementation MyAssetsGroup

- (id)initWithAssetGroup:(ALAssetsGroup *)group
{
    self  = [super init];
    if (self) {
        _assetGroup = group;
        _groupIdentifier = [(NSURL *)[group valueForProperty:ALAssetsGroupPropertyURL] absoluteString];
        _groupName = [group valueForProperty:ALAssetsGroupPropertyName];
        
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        _numberOfPhotos = [group numberOfAssets];
        
        [group setAssetsFilter:[ALAssetsFilter allVideos]];
        _numberOfVideos = [group numberOfAssets];
        
        _groupThumbnail = [UIImage imageWithCGImage:group.posterImage];
    }
    return self;
}

- (id)initWithPHAssetCollection:(PHAssetCollection *)collection
              photosFetchResult:(PHFetchResult *)photosFetchResult
              videosFetchResult:(PHFetchResult *)videosFetchResult
{
    self = [super init];
    if (self) {
        _assetGroup = collection;
        _groupIdentifier = [collection localIdentifier];
        _groupName = [collection localizedTitle];

        _numberOfPhotos = [photosFetchResult count];
        _numberOfVideos = [videosFetchResult count];
        
        PHAsset *firstPhotoAsset = [photosFetchResult firstObject];
        PHAsset *firstVideoAsset = [videosFetchResult firstObject];
        PHAsset *coverAsset = firstPhotoAsset ? firstPhotoAsset : firstVideoAsset;
        
        if (firstVideoAsset && firstPhotoAsset) {
            coverAsset = [[firstPhotoAsset creationDate] isLaterThanDate:[firstVideoAsset creationDate]] ? firstPhotoAsset : firstVideoAsset;
        }

        if (coverAsset) {
            __weak MyAssetsGroup *weakSelf = self;
           //  weakSelf.groupThumbnail = [coverAsset minThumbnail];
            PHImageManager *imageManager =  [PHImageManager defaultManager];
            [imageManager requestImageForAsset:coverAsset
                                    targetSize:CGSizeMake(120 * SCREEN_SCALE, 120 * SCREEN_SCALE)
                                   contentMode:PHImageContentModeAspectFill
                                       options:nil
                                 resultHandler:^(UIImage *result, NSDictionary *info) {
                                     dispatch_async(dispatch_get_main_queue(), ^{
                                         weakSelf.groupThumbnail = result;
                                     });
                                 }];
        }
    }
    return self;
}

+ (MyAssetsGroup *)getMyGroupForIdentifier:(NSString *)identifier inArray:(NSArray *)groups
{
    for (int i = 0; i < groups.count; i++) {
        MyAssetsGroup *tempGroup = groups[i];
        if ([[tempGroup groupIdentifier] isEqualToString:identifier]) {
            return tempGroup;
        }
    }

    return nil;
}

- (BOOL)isEqual:(id)object
{
    if ([super isEqual:object]) {
        return YES;
    }
    
    if ([object isKindOfClass:[MyAssetsGroup class]]) {
        MyAssetsGroup *otherGroup = object;
        if ([otherGroup.groupIdentifier isEqualToString:self.groupIdentifier]) {
            return YES;
        }
    }

    return NO;
}

- (NSUInteger)hash
{
    return [_groupIdentifier hash];
}

@end

@interface ALAssetsGroupEnumerator()

@property (nonatomic, strong) NSOperationQueue *enumQueue;

// Photo Kit
@property (nonatomic, strong) PHFetchOptions *photosFetchOptions;
@property (nonatomic, strong) PHFetchOptions *videosFetchOptions;

@property (nonatomic, strong) NSMutableArray *collectionsFetchResults;

@end

@implementation ALAssetsGroupEnumerator

- (id)init
{
    self = [super init];
    if (self) {
        if (NSClassFromString(@"PHPhotoLibrary")) {
            [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
            
            _photosFetchOptions = [PHFetchOptions new];
            _photosFetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];
            _photosFetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            
            _videosFetchOptions = [PHFetchOptions new];
            _videosFetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeVideo];
            _videosFetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            
            _imageManager = [[PHCachingImageManager alloc] init];
            
            _cachedPhotos = [[NSMutableDictionary alloc] init];
        } else {
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(assetsLibraryUpdated:)
                                                         name:ALAssetsLibraryChangedNotification
                                                       object:nil];
            
            _cachedPhotos = [[NSMutableDictionary alloc] init];
            
            _enumQueue = [[NSOperationQueue alloc] init];
            _enumQueue.maxConcurrentOperationCount = 1;
        }
    }
    return self;
}

+ (ALAssetsGroupEnumerator *)sharedInstance
{
    // structure used to test whether the block has completed or not
    static dispatch_once_t p = 0;

    // initialize sharedObject as nil (first call only)
    __strong static id _sharedObject = nil;
    
    // executes a block object once and only once for the lifetime of an application
    dispatch_once(&p, ^{
        _sharedObject = [[self alloc] init];
        
        if (NSClassFromString(@"PHPhotoLibrary")) {
            [(ALAssetsGroupEnumerator *)_sharedObject enumAlbumsForiOS8];
        } else {
            [(ALAssetsGroupEnumerator *)_sharedObject enumAllGroups];
        }
    });
    
    // returns the same object each time
    return _sharedObject;
}

+ (BOOL)hasPermissionToAccessPhotoAndAlert:(BOOL)alert
{
    if (NSClassFromString(@"PHPhotoLibrary")){
        
        PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
        if (authStatus == PHAuthorizationStatusDenied ||
            authStatus == PHAuthorizationStatusRestricted) {
            
            if (alert) {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:QWImagePickerLocalizedString(@"This app does not have access to your photos!", nil)
                                                                 message:QWImagePickerLocalizedString(@"You can enable access in Privacy Settings.", nil)
                                                                delegate:nil
                                                       cancelButtonTitle:QWImagePickerLocalizedString(@"I know", nil)
                                                       otherButtonTitles:nil];
                [alert show];
            }
            
            return NO;
        }
        
    }else
    {
        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
        
        if (authStatus == ALAuthorizationStatusDenied ||
            authStatus == ALAuthorizationStatusRestricted) {
            
            if (alert) {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:QWImagePickerLocalizedString(@"This app does not have access to your photos!", nil)
                                                                 message:QWImagePickerLocalizedString(@"You can enable access in Privacy Settings.", nil)
                                                                delegate:nil
                                                       cancelButtonTitle:QWImagePickerLocalizedString(@"I know", nil)
                                                       otherButtonTitles:nil];
                [alert show];
            }
            
            return NO;
        }
    }

    
    return YES;
}

+ (BOOL)hasPermissionToAccessCameraAndAlert:(BOOL)alert
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        if (authStatus == AVAuthorizationStatusAuthorized) {
            return YES;
        } else if (authStatus == AVAuthorizationStatusNotDetermined) {
            return YES;
        }
        
        if (alert) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:QWImagePickerLocalizedString(@"This app does not have access to your camera!", nil)
                                                             message:QWImagePickerLocalizedString(@"You can enable access in Privacy Settings.", nil)
                                                            delegate:nil
                                                   cancelButtonTitle:QWImagePickerLocalizedString(@"I know", nil)
                                                   otherButtonTitles:nil];
            [alert show];
        }
        
        return NO;
    } else {
        return YES;
    }
}

- (AssetsList *)getAssetsListOfGroup:(MyAssetsGroup *)group
{
    if (group) {
        AssetsList *assList = [self.cachedPhotos objectForKey:group.groupIdentifier];
        if (assList) {
            return assList;
        } else {
            if (NSClassFromString(@"PHPhotoLibrary")) {
                PHFetchResult *photosFetchResult = [PHAsset fetchAssetsInAssetCollection:group.assetGroup
                                                                                 options:_photosFetchOptions];
                PHFetchResult *videosFetchResult = [PHAsset fetchAssetsInAssetCollection:group.assetGroup
                                                                                 options:_videosFetchOptions];

                AssetsList *assList = [[AssetsList alloc] initWithAssetsGroup:group
                                                            photosFetchResult:photosFetchResult
                                                            videosFetchResult:videosFetchResult];
                
                [self.cachedPhotos setObject:assList forKey:group.groupIdentifier];
                
                [assList loadAssetsForPHAssetsCollection];
            } else {
                AssetsList *assList = [[AssetsList alloc] initWithAssetsGroup:group
                                                                     delegate:self];
                
                [self.cachedPhotos setObject:assList forKey:group.groupIdentifier];
                
                [assList loadAssetsWithEnumerationBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                }];

            }

            return assList;
        }
    }

    NSAssert(0, @"Should not have group now");
    return nil;
}

- (NSMutableArray *)getNotEmptyGroupsForPhoto:(BOOL)forPhoto
{
    NSPredicate *predict = forPhoto ? [NSPredicate predicateWithFormat:@"numberOfPhotos > 0"] :
                                      [NSPredicate predicateWithFormat:@"numberOfVideos > 0"];
    NSMutableArray *result = [[self.curGroups filteredArrayUsingPredicate:predict] mutableCopy];
    
    // 如果都是空的，显示默认相册
    if ([result count] == 0 && [self.curGroups count] > 0) {
        [result addObject:[self.curGroups firstObject]];
    }

    return result;
}

#pragma mark -
#pragma mark AssetsLibrary of iOS 6 and iOS 7

- (void)assetsLibraryUpdated:(NSNotification *)notify
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary *dict = notify.userInfo;
        if (dict == nil) {
            [self.curGroups removeAllObjects];
            [self.cachedPhotos removeAllObjects];

            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ENUM_GROUP_FINISHED
                                                                object:nil userInfo:nil];
            [self enumAllGroups];
        } else if ([dict count] > 0) {
            NSSet *updatedGroups = [dict objectForKey:ALAssetLibraryUpdatedAssetGroupsKey];
            NSSet *insertedGroups = [dict objectForKey:ALAssetLibraryInsertedAssetGroupsKey];
            NSSet *deletedGroups = [dict objectForKey:ALAssetLibraryDeletedAssetGroupsKey];
            if ([deletedGroups count]) {
                BOOL deleted = NO;
                
                for (NSURL *groupUrl in deletedGroups) {
                    MyAssetsGroup *selGroup = [MyAssetsGroup getMyGroupForIdentifier:[groupUrl absoluteString] inArray:self.curGroups];
                    
                    if (selGroup) {
                        deleted = YES;
                        [self.curGroups removeObject:selGroup];
                        
                        NSDictionary *dict = @{@"deletedGroup":selGroup};
                        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ENUM_GROUP_FINISHED object:nil userInfo:dict];

                        AssetsList *lastList = [self.cachedPhotos objectForKey:groupUrl.absoluteString];
                        lastList.stopQuery = YES;
                        
                        [self.cachedPhotos removeObjectForKey:groupUrl.absoluteString];
                    }
                }
            }
            
            if ([insertedGroups count]) {
                ALAssetsLibrary *library = [QWImageMangerConfig sharedAssetsLibrary];
                
                for (NSURL *groupUrl in insertedGroups) {
                    [library groupForURL:groupUrl
                             resultBlock:^(ALAssetsGroup *group) {
                                 if (!group) {
                                     return;
                                 }

                                 MyAssetsGroup *myGroup = [[MyAssetsGroup alloc] initWithAssetGroup:group];
                                 if (![self.curGroups containsObject:myGroup]) {
                                     
                                     [self.curGroups addObject:myGroup];
                                     
                                     AssetsList *lastList = [self.cachedPhotos objectForKey:myGroup.groupIdentifier];
                                     lastList.stopQuery = YES;
                                     
                                     AssetsList *assList = [[AssetsList alloc] initWithAssetsGroup:myGroup delegate:self];
                                     [self.cachedPhotos setObject:assList forKey:myGroup.groupIdentifier];

                                     [assList loadAssetsWithEnumerationBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                                     }];
                                 }
                             }
                            failureBlock:^(NSError *error) {
                               // //DebugLog(@"get group for url failed: %@", groupUrl);
                            }];
                }
            }

            if ([updatedGroups count]) {
                ALAssetsLibrary *library = [QWImageMangerConfig sharedAssetsLibrary];
                
                for (NSURL *groupUrl in updatedGroups) {
                    MyAssetsGroup *selGroup = [MyAssetsGroup getMyGroupForIdentifier:[groupUrl absoluteString] inArray:self.curGroups];
                    
                    if (selGroup) {
                        [library groupForURL:groupUrl
                                 resultBlock:^(ALAssetsGroup *group) {
                                     if (!group) {
                                         [self.curGroups removeObject:selGroup];
                                         
                                         NSDictionary *dict = @{@"deletedGroup":selGroup};
                                         [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ENUM_GROUP_FINISHED object:nil userInfo:dict];
                                         
                                         AssetsList *lastList = [self.cachedPhotos objectForKey:groupUrl.absoluteString];
                                         lastList.stopQuery = YES;
                                         
                                         [self.cachedPhotos removeObjectForKey:groupUrl.absoluteString];
                                     } else {
                                         NSInteger index = [self.curGroups indexOfObject:selGroup];
                                         if (index != NSNotFound && self.curGroups.count) {
                                             MyAssetsGroup *myGroup = [[MyAssetsGroup alloc] initWithAssetGroup:group];
                                             [self.curGroups replaceObjectAtIndex:index withObject:myGroup];
                                         }

                                         AssetsList *lastList = [self.cachedPhotos objectForKey:selGroup.groupIdentifier];
                                         lastList.stopQuery = YES;

                                         AssetsList *assList = [[AssetsList alloc] initWithAssetsGroup:selGroup delegate:self];
                                         [self.cachedPhotos setObject:assList forKey:selGroup.groupIdentifier];
                                         
                                         [assList loadAssetsWithEnumerationBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                                         }];
                                     }
                                 } failureBlock:^(NSError *error) {
                                     //DebugLog(@"get group for url failed: %@", groupUrl);
                                 }];
                    }
                }
            }
        }
    });
}

- (void)enumAllGroups
{
    // Load Albums into assetGroups
    if (_isDuringEnum) {
        return;
    }

    _isDuringEnum = YES;

    ALAssetsLibrary *library = [QWImageMangerConfig sharedAssetsLibrary];
    _curGroups = [NSMutableArray array];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @autoreleasepool {
            // Group enumerator Block
            void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop){
                if (group == nil) {
                    _isDuringEnum = NO;
                    return;
                }
                
                MyAssetsGroup *myGroup = [[MyAssetsGroup alloc] initWithAssetGroup:group];
                
                // 相机胶卷放最前面，然后是照片流
                if ([[group valueForProperty:ALAssetsGroupPropertyType] intValue] == ALAssetsGroupSavedPhotos) {
                    [self.curGroups insertObject:myGroup atIndex:0];
                } else if ([[group valueForProperty:ALAssetsGroupPropertyType] intValue] == ALAssetsGroupPhotoStream) {
                    MyAssetsGroup *firstGroup = [self.curGroups firstObject];
                    if (firstGroup &&
                        [[firstGroup.assetGroup valueForProperty:ALAssetsGroupPropertyType] intValue] == ALAssetsGroupSavedPhotos) {
                        [self.curGroups insertObject:myGroup atIndex:1];
                    } else {
                        [self.curGroups insertObject:myGroup atIndex:0];
                    }
                } else {
                    [self.curGroups addObject:myGroup];
                }
                
                AssetsList *assList = [[AssetsList alloc] initWithAssetsGroup:myGroup delegate:self];
                [self.cachedPhotos setObject:assList forKey:myGroup.groupIdentifier];

                [group setAssetsFilter:[ALAssetsFilter allAssets]];
                [assList loadAssetsWithEnumerationBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                }];
            };

            // Group Enumerator Failure Block
            void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
                self.enumFailed = YES;
                //DebugLog(@"A problem occured %@", [error description]);

                _isDuringEnum = NO;
            };

            // Enumerate Albums
            [library enumerateGroupsWithTypes:ALAssetsGroupAll
                                   usingBlock:assetGroupEnumerator
                                 failureBlock:assetGroupEnumberatorFailure];
        }
    });
}

#pragma mark AssetsListDelegate
- (void)asstesListenumFinished:(AssetsList *)list
{
    if (list) {
        NSDictionary *dict = @{@"updatedList":list};
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ENUM_GROUP_FINISHED
                                                            object:list userInfo:dict];
    }
}

#pragma mark -
#pragma mark PHPhotoLibrary for iOS 8

- (void)photoLibraryDidChange:(PHChange *)changeInstance
{

    // Call might come on any background queue. Re-dispatch to the main queue to handle it.
    dispatch_async(dispatch_get_main_queue(), ^{

        NSMutableArray *updatedCollectionsFetchResults = nil;
        NSMutableArray *removedObjects = [NSMutableArray array];
       // PHObjectChangeDetails *details = [changeInstance changeDetailsForObject:changeInstance];
        
        for (PHFetchResult *collectionsFetchResult in self.collectionsFetchResults) {
            PHFetchResultChangeDetails *changeDetails = [changeInstance changeDetailsForFetchResult:collectionsFetchResult];
            if (changeDetails) {
                if (!updatedCollectionsFetchResults) {
                    updatedCollectionsFetchResults = [self.collectionsFetchResults mutableCopy];
                }
                [updatedCollectionsFetchResults replaceObjectAtIndex:[self.collectionsFetchResults indexOfObject:collectionsFetchResult] withObject:[changeDetails fetchResultAfterChanges]];
            }
            
            [removedObjects addObjectsFromArray:[changeDetails removedObjects]];
        }

        if (updatedCollectionsFetchResults) {
            self.collectionsFetchResults = updatedCollectionsFetchResults;
            [self resetPHAssetCollectionArray];
            NSDictionary *dict = @{@"updatePHAssetCollections":@(YES)};
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ENUM_GROUP_FINISHED
                                                                object:removedObjects
                                                            userInfo:dict];
        }else
        {
            [self enumAlbumsForiOS8];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ENUM_GROUP_FINISHED
                                                                object:removedObjects
                                                              userInfo:nil];
        }

        NSArray *assetsLists = [self.cachedPhotos allValues];
        for (int i = 0; i < assetsLists.count; i++) {
            AssetsList *assestList = assetsLists[i];
            PHFetchResult *photosFetchResult = assestList.photosFetchResult;
            PHFetchResult *videosFetchResult = assestList.videosFetchResult;

            // check if there are changes to the assets (insertions, deletions, updates)
            PHFetchResultChangeDetails *photosChanges = [changeInstance changeDetailsForFetchResult:photosFetchResult];
            PHFetchResultChangeDetails *videosChanges = [changeInstance changeDetailsForFetchResult:videosFetchResult];

            if (photosChanges || videosChanges) {
                // get the new fetch result
                photosFetchResult = [photosChanges fetchResultAfterChanges];
                videosFetchResult = [videosChanges fetchResultAfterChanges];

                AssetsList *assList = [[AssetsList alloc] initWithAssetsGroup:assestList.myGroup
                                                            photosFetchResult:photosFetchResult
                                                            videosFetchResult:videosFetchResult];
                
                [self.cachedPhotos setObject:assList forKey:assestList.myGroup.groupIdentifier];
                [assList loadAssetsForPHAssetsCollection];
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                if (photosChanges != nil){
                       [dict setValue:photosChanges forKey:@"PhotosChanges"];
                }
                if (videosChanges != nil){
                    [dict setValue:videosChanges forKey:@"VideosChanges"];
                }
                if (assestList.myGroup != nil){
                    [dict setValue:assestList.myGroup forKey:@"CurrentGroup"];
                }

                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ENUM_GROUP_FINISHED
                                                                    object:nil
                                                                  userInfo:dict];
            }
        }
    });
}

- (void)enumAlbumsForiOS8
{
    
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    NSMutableArray *tempArray = [NSMutableArray array];
    if (smartAlbums) {
        [tempArray addObject:smartAlbums];
    }
    
    if (userAlbums) {
        [tempArray addObject:userAlbums];
    }
    self.collectionsFetchResults = tempArray;
    [self resetPHAssetCollectionArray];
}

- (void)resetPHAssetCollectionArray
{
    // 相机胶卷放最前面，然后是照片流
    NSMutableArray *albums = [NSMutableArray array];
    
    for (int i = 0; i < self.collectionsFetchResults.count; i++) {
        PHFetchResult *collections = [self.collectionsFetchResults objectAtIndex:i];
        
        [collections enumerateObjectsUsingBlock:^(PHAssetCollection *obj, NSUInteger idx, BOOL *stop){
            if (obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumBursts ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumFavorites ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumPanoramas ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumRecentlyAdded ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumGeneric ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumSlomoVideos ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumTimelapses ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumVideos ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeAlbumCloudShared ||
                obj.assetCollectionSubtype == PHAssetCollectionSubtypeAlbumMyPhotoStream ||
                obj.assetCollectionSubtype == 211 ||    //屏幕快照  只有iOS9以后可以用 所以用数字代替
                obj.assetCollectionSubtype == 210 ||  //自拍     只有iOS9以后可以用 所以用数字代替
                obj.assetCollectionType == PHAssetCollectionTypeAlbum
                    ) {

                PHFetchResult *photosFetchResult = [PHAsset fetchAssetsInAssetCollection:obj
                                                                                 options:_photosFetchOptions];
                PHFetchResult *videosFetchResult = [PHAsset fetchAssetsInAssetCollection:obj
                                                                                 options:_videosFetchOptions];

                MyAssetsGroup *myGroup = [[MyAssetsGroup alloc] initWithPHAssetCollection:obj
                                                                        photosFetchResult:photosFetchResult
                                                                        videosFetchResult:videosFetchResult];
                
                if (obj.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary) {
                    [albums insertObject:myGroup atIndex:0];
                } else if (obj.assetCollectionSubtype == PHAssetCollectionSubtypeAlbumMyPhotoStream) {
                    PHAssetCollection *firstCol = [[albums firstObject] assetGroup];

                    if (firstCol.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary) {
                        [albums insertObject:myGroup atIndex:1];
                    } else {
                        [albums insertObject:myGroup atIndex:0];
                    }
                } else {
                    [albums addObject:myGroup];
                }

                AssetsList *assList = [[AssetsList alloc] initWithAssetsGroup:myGroup
                                                            photosFetchResult:photosFetchResult
                                                            videosFetchResult:videosFetchResult];
                
                [self.cachedPhotos setObject:assList forKey:myGroup.groupIdentifier];
                
                [assList loadAssetsForPHAssetsCollection];
            }
        }];
    }

    self.curGroups = albums;
}

@end